<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Adaccountreport_model extends My_Model
{
   
    public function __construct()
    {
        parent::__construct();
        $this->model_name="adword account report";
        $this->tablename="adaccountreport";   
    }
   
    

    public function addinsert($item)
    {
        $data=$this->get_item_by_where(["acccountid"=>$item[14],"reportdate"=>$item[3]]);
        if(!$data)
        {
            $newdata=[
                "acccountid"=>$item[14],
                "reportdate"=>$item[3],
                "impressions"=>$item[5],
                "click"=>$item[4],
                "ctr"=>str_replace("%","",$item[6]),
                "cost"=>$item[7],
                "conversions"=>$item[8],
                "conversionrate"=>str_replace("%","",$item[9]),
                "conversionvalue"=>$item[12],
                "averagecpc"=>$item[10],
                "costperconversion"=>$item[11],
            ];
            $newdata['convucost']=sprintf("%.2f",$newdata["conversionvalue"]/$newdata["cost"]);
            return $this->add_item($newdata);
        }
    }

    public function getdetail($accountid,$timelimit)
    {
        $where="acccountid=".$accountid." and reportdate between '".$timelimit["start"]."' and '".$timelimit["end"]."'";
        $result=$this->get_items_by_where($where);
        return $result;
    }

    public function getrangelist($timelimit)
    {
        $sql="select acccountid,sum(impressions) as impressions,sum(click) as click,sum(cost) as cost,sum(conversions) as conversions,sum(	conversionvalue) as conversionvalue from ".$this->table_prefix.$this->tablename." where reportdate between '".$timelimit["start"]."' and '".$timelimit["end"]."'  group by acccountid";
        $query=$this->db->query($sql);
        $res=$query->result_array();
        return $res;
    }
    
    
    public function getitembykey($val,$key="id")
    {
        $where=array($key=>$val);
        return $this->get_item_by_where($where);
    }

    public function getfilter($where)
    {
        return $this->get_items_by_where($where);
    }
    
    public function create($data){
    
        return $this->add_item($data);         
    }
    
    public function update($id,$data){
        if(is_array($id))
        {
            $where="id in (".implode(",",$id).")";
          
        }else{
            $where=array("id"=>$id);
        
        }
        return $this->update_item($where,$data);
    }

   
}
